package com.verykim.video;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

@SuppressWarnings("serial")
public class StaticFileServlet extends HttpServlet {

	final static String IMG_THUMB = "^/thumb/[A-Za-z0-9_-]+$";
	final static String DOWNLOAD = "^/download/[A-Za-z0-9_-]+$";

	@Override
	public void doGet(final HttpServletRequest req,
			final HttpServletResponse resp) throws IOException {

		final String URI = req.getRequestURI();
		resp.getWriter().print(URI);
		if (URI.matches(IMG_THUMB)) {

			/*
			 * final String referer = req.getHeader("referer"); if (null ==
			 * referer || !referer.startsWith(req.getScheme() + "://" +
			 * req.getServerName())) { // resp.sendRedirect("static/load.png");
			 * resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); return; }
			 */

			final String etag = URI.substring("/thumb/".length());

			final String previousToken = req.getHeader("If-None-Match");
			if (previousToken != null && previousToken.equals(etag)) {
				resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
				resp.setHeader("Last-Modified",
						req.getHeader("If-Modified-Since"));
				return;
			}

			final TimeZone timeZoneSH = TimeZone.getTimeZone("GMT+8");
			final Calendar cal = Calendar.getInstance();
			cal.setTimeZone(timeZoneSH);
			final Date lastModified = cal.getTime();

			resp.setHeader("Etag", etag);
			resp.setDateHeader("Expires", lastModified.getTime() + 86400 * 1000);

			resp.setDateHeader("Last-Modified", lastModified.getTime());
			resp.setHeader("Cache-Control", "public, max-age=86400");// 1day
			final BlobstoreService bs = BlobstoreServiceFactory
					.getBlobstoreService();
			final BlobKey blobKey = new BlobKey(etag);
			bs.serve(blobKey, resp);

		} else if (URI.matches("^([A-Za-z0-9_-]+)(\\.)(css|js)$")) {
			resp.setContentType("text/css");// application/x-javascript

		} else if (URI.matches("^/feed.xml$")) {
			resp.setContentType("image/jpeg");
			resp.setHeader("Content-Disposition", "attachment; filename="
					+ URLEncoder.encode("attachment", "UTF-8"));

		}
	}

	@Override
	public void doPost(final HttpServletRequest req,
			final HttpServletResponse resp) throws IOException {
		resp.sendError(HttpServletResponse.SC_FORBIDDEN);
	}
}
